﻿using Nirvana;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.UI;

public class I18NToolEditor : EditorWindow
{
    private I18NFont i18NFont;
    private bool isCollect = false;
    private string[] Scenes;
    private int sceneIndex = 0;
    private UnityEngine.SceneManagement.Scene scene;
    private int collect = 0;
    private int Count = 0;

    [MenuItem("Tools/TextI18N(多国语言)", false)]
    public static void Init()
    {
        Rect rect = new Rect(0f, 0f, 500f, 500f);
        I18NToolEditor windowWithRect = EditorWindow.GetWindowWithRect<I18NToolEditor>(rect, false, "I18N Text Checker");
        windowWithRect.Show();
    }

    private void OnGUI()
    {
        GUILayout.Space(10f);
        EditorGUILayout.LabelField("I18N Text Checker", GUITheme.LabelTitleStyle, new GUILayoutOption[0]);
        GUILayout.Space(10f);
        GUILayout.Label("Text Rules:", GUITheme.TitleStyle, new GUILayoutOption[0]);

        GUILayout.Space(10f);
        EditorGUILayout.Space();
        if (GUILayoutEx.ActionButton("I18N Cache Clear", new GUILayoutOption[0]))
        {
            I18N.ClearCache();
        }

        EditorGUILayout.Space();
        if (GUILayoutEx.ActionButton("检测所有Prefab的Text,并添加TextI18N", new GUILayoutOption[0]))
        {
            CheckPrefab();
        }

        if (GUILayoutEx.ActionButton("检测所有场景的Text,并添加TextI18N", new GUILayoutOption[0]))
        {
            CheckScene();
        }

        if (GUILayoutEx.ActionButton("查找指定MonoBehaviour", new GUILayoutOption[0]))
        {
            FindComponentEditor.Open();
        }
        
    }

    private void CheckPrefab()
    {
        base.hideFlags = HideFlags.HideAndDontSave;

        if (i18NFont == null)
        {
            i18NFont = FindI18NFont();
            if (i18NFont == null)
            {
                Debug.LogError("Dont find Font for :I18NFont");
                return;
            }
        }
        //string[] paths = new string[] { "Assets/Scripts/Nirvana/Language" };
        //string[] array = AssetDatabase.FindAssets("t:prefab", paths);
        string[] paths = new string[] { "Assets/Resources/UI" };
        string[] array = AssetDatabase.FindAssets("t:prefab", paths);
        using (ProgressIndicator progress = new ProgressIndicator("generate asset keys", array.Length))
        {
            for (int i = 0; i < array.Length; i++)
            {
                string asset = array[i];
                string path = AssetDatabase.GUIDToAssetPath(asset);
               // Debug.LogFormat("-find-->>>{0} {1}" , path, asset);
                progress.SetProgress(i);
                progress.ShowForce("check asset:{0}", asset);
                
                Object[] arrayObjs = AssetDatabase.LoadAllAssetsAtPath(path);

                if (arrayObjs.Length == 0)
                {
                    Debug.LogFormat("<color=#00ff00>--->The path: {0} can not load. </color> ", path);
                    continue;
                }
                if (arrayObjs[0] == null)
                {
                    continue;
                }

                foreach (Object @object in arrayObjs)
                {
                    if (!(@object == null))
                    {
                        Text txt = @object as Text;
                        if (txt != null)
                        {
                            if (txt.font == null) continue;
                            if (txt.font.name == "SourceHanSansCN-Heavy" || txt.font.name == "Arial" || txt.font.name == "SIMHEI")//目前默认字体才替换
                            {
                                if (txt.gameObject.GetComponent<Nirvana.TextI18N>())
                                {
                                    continue;
                                }
                                Debug.LogFormat("<color=#4973E1>--->check {0} {1} </color> ", path, @object.name);
                                var txti18n = txt.gameObject.AddComponent<Nirvana.TextI18N>();
                                txti18n.I18NFont = i18NFont;
                                EditorUtility.SetDirty(txti18n);
                                EditorUtility.SetDirty(txt.gameObject);
                            }
                        }
                    }
                }
            }
        }
        

        AssetDatabase.SaveAssets();
    }

    private void CheckScene()
    {
        base.hideFlags = HideFlags.HideAndDontSave;
        if (i18NFont == null)
        {
            i18NFont = FindI18NFont();
            if (i18NFont == null)
            {
                Debug.LogError("Dont find Font for :I18NFont");
                return;
            }
        }

        EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
        //string[] paths = new string[] { "Assets/Scripts/Nirvana/Language" };
        //Scenes = AssetDatabase.FindAssets("t:scene", paths);
        Scenes = AssetDatabase.FindAssets("t:scene", new string[] { "Assets/Scenes" });
        LoadScene();
        EditorApplication.update += Update;

    }
    void Update()
    {
        if (isCollect)
        {
            if (collect < Count)
            {
                collect++;
            }
            else
            {
                isCollect = false;
                LoadScene();
            }
        }
    }
    private void LoadScene()
    {
        if (Scenes == null) return;
        if (scene != null)
        {
            EditorSceneManager.CloseScene(scene, true);
        }

        if (sceneIndex >= Scenes.Length)
        {
            StopSceneCollectShader();
        }
        else
        {
            bool isMain = false;
            do
            {
                string asset = Scenes[sceneIndex];
                string path = AssetDatabase.GUIDToAssetPath(asset);
                bool isSave = false;
                scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive);
                isMain = true;
                foreach (GameObject game in scene.GetRootGameObjects())
                {
                    foreach (var txt in game.GetComponentsInChildren<Text>(true))
                    {
                        if (txt != null)
                        {
                            if (txt.font == null) continue;
                            if (txt.font.name == "SourceHanSansCN-Heavy" || txt.font.name == "Arial" || txt.font.name == "SIMHEI")//目前默认字体才替换
                            {
                                if (txt.gameObject.GetComponent<TextI18N>())
                                {
                                    continue;
                                }
                                isSave = true;
                                var txti18n = txt.gameObject.AddComponent<TextI18N>();
                                txti18n.I18NFont = i18NFont;
                                EditorUtility.SetDirty(txti18n);
                                EditorUtility.SetDirty(txt.gameObject);

                                PrefabAssetType prefabType = PrefabUtility.GetPrefabAssetType(txt.gameObject);
                                if (prefabType == PrefabAssetType.Regular)
                                {
                                    var root = PrefabUtility.GetNearestPrefabInstanceRoot(txt.gameObject);
                                    if (root == null) continue;
                                    Object tg = PrefabUtility.GetCorrespondingObjectFromSource(root);
                                    PrefabUtility.ReplacePrefab(root, tg, ReplacePrefabOptions.ConnectToPrefab);
                                }
                            }
                        }

                    }
                }
                collect = 0;
                Count = 10;
                if (isSave)
                {
                    EditorSceneManager.SaveScene(scene);
                }
                sceneIndex++;
            } while(!isMain); 
        }
        AssetDatabase.Refresh();
        isCollect = true;
    }

    private void StopSceneCollectShader()
    {
        if (scene != null)
        {
            EditorSceneManager.CloseScene(scene, true);
        }

        EditorApplication.update -= Update;

        collect = 0;
        Count = 0;

        Scenes = null;
        isCollect = false;
        sceneIndex = 0;
        EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
    }

    private I18NFont FindI18NFont()
    {
        string[] array = AssetDatabase.FindAssets("t:I18NFont");
        if (array.Length == 0)
        {
            return null;
        }
        string text = AssetDatabase.GUIDToAssetPath(array[0]);
        return AssetDatabase.LoadAssetAtPath<I18NFont>(text);
    }

}
